<template>
  <div class="ai-chat">
    <div class="chat-container">
      <div class="chat-header">
        <h2>算法助手</h2>
        <p>有任何算法相关的问题，都可以向我咨询</p>
      </div>

      <div class="messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" 
             :key="index" 
             :class="['message', message.role]">
          <div class="avatar">
            <el-avatar :icon="message.role === 'user' ? UserFilled : Service" />
          </div>
          <div class="content">
            <div class="text" v-html="formatMessage(message.content)"></div>
            <div class="time">{{ formatTime(message.time) }}</div>
          </div>
        </div>
        <div v-if="loading" class="message assistant">
          <div class="avatar">
            <el-avatar :icon="Service" />
          </div>
          <div class="content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <div class="input-area">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          resize="none"
          @keyup.enter.exact="handleSend"
        />
        <div class="button-group">
          <el-button type="primary" :disabled="!userInput.trim() || loading" @click="handleSend">
            发送
          </el-button>
          <el-button @click="clearChat" :disabled="messages.length === 0">
            清空对话
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { UserFilled, Service } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AIChat',
  components: {
    UserFilled,
    Service
  },
  setup() {
    const messages = ref([
      {
        role: 'assistant',
        content: '你好！我是算法助手，有任何算法相关的问题都可以问我。',
        time: new Date()
      }
    ])
    const userInput = ref('')
    const loading = ref(false)
    const messagesContainer = ref(null)

    const scrollToBottom = async () => {
      await nextTick()
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    }

    const formatTime = (time) => {
      return new Date(time).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const formatMessage = (content) => {
      // 简单的文本处理，将换行符转换为<br>标签
      return content.replace(/\n/g, '<br>')
    }

    const handleSend = async () => {
      const message = userInput.value.trim()
      if (!message || loading.value) return

      // 添加用户消息
      messages.value.push({
        role: 'user',
        content: message,
        time: new Date()
      })
      userInput.value = ''
      scrollToBottom()

      // 发送请求
      loading.value = true
      try {
        const response = await axios.post('/api/chat', {
          question: message,
          userId: 1  // 这里可以根据实际登录用户ID修改
        })

        if (response.data.code === 200) {
          const responseData = response.data.data
          // 检查是否包含错误信息
          if (responseData.answer.includes('AI服务暂时不可用')) {
            ElMessage.error('AI服务暂时不可用，请稍后再试')
            messages.value.push({
              role: 'assistant',
              content: '抱歉，我现在暂时无法回答您的问题，请稍后再试。',
              time: new Date(responseData.createTime)
            })
          } else {
            messages.value.push({
              role: 'assistant',
              content: responseData.answer,
              time: new Date(responseData.createTime)
            })
          }
        } else {
          ElMessage.error(response.data.message || '请求失败')
          messages.value.push({
            role: 'assistant',
            content: '抱歉，系统出现错误，请稍后重试。',
            time: new Date()
          })
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败，请稍后重试')
        messages.value.push({
          role: 'assistant',
          content: '抱歉，网络连接出现问题，请检查您的网络连接后重试。',
          time: new Date()
        })
      } finally {
        loading.value = false
        scrollToBottom()
      }
    }

    const clearChat = () => {
      ElMessageBox.confirm(
        '确定要清空所有对话记录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        messages.value = [{
          role: 'assistant',
          content: '你好！我是算法助手，有任何算法相关的问题都可以问我。',
          time: new Date()
        }]
        ElMessage.success('对话已清空')
      }).catch(() => {})
    }

    onMounted(() => {
      scrollToBottom()
    })

    return {
      messages,
      userInput,
      loading,
      messagesContainer,
      handleSend,
      clearChat,
      formatTime,
      formatMessage,
      UserFilled,
      Service
    }
  }
}
</script>

<style scoped>
.ai-chat {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  height: calc(100vh - 120px);
}

.chat-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
}

.chat-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5em;
}

.chat-header p {
  margin: 10px 0 0;
  color: #606266;
  font-size: 0.9em;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message .avatar {
  margin-right: 12px;
}

.message .content {
  flex: 1;
  background-color: #f4f4f5;
  padding: 12px 16px;
  border-radius: 8px;
  position: relative;
  max-width: 80%;
}

.message.user {
  flex-direction: row-reverse;
}

.message.user .avatar {
  margin-right: 0;
  margin-left: 12px;
}

.message.user .content {
  background-color: #ecf5ff;
}

.message .time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.button-group {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 4px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #909399;
  border-radius: 50%;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: 0.2s; }
.typing-indicator span:nth-child(2) { animation-delay: 0.3s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.4s; }

@keyframes typing {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

:deep(.content pre) {
  background-color: #282c34;
  border-radius: 6px;
  padding: 16px;
  margin: 8px 0;
  overflow-x: auto;
}

:deep(.content code) {
  font-family: 'Fira Code', monospace;
  font-size: 14px;
}

:deep(.content p) {
  margin: 8px 0;
  line-height: 1.6;
}

:deep(.el-textarea__inner) {
  resize: none !important;
}
</style> 